# coding=UTF-8

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from live_api.tools.Output_Helper import *
import live_api.tools.utils_file as ufile
from live_api.tools.utils_datetime import *
from live_api.tools.sms import verifycode


# 找回忘记密码(重设密码)
@csrf_exempt
def changepwd(request):
    db = DB.getDB()
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user", "new_pwd", "old_pwd")
        try:
            sql = sqlr("select * from user where id=$id_user and cpwd=$old_pwd", info)
            # print(sql)

            n, rows = db.query(sql)
            if n > 0:
                sql = sqlr("update user set cpwd=$new_pwd where id=$id_user", info)
                # print(sql)
                db.execute(sql)
                ret.code = 200
                ret.msg = "请求成功!"
            else:
                ret.code = 1004
                ret.msg = "密码错误!"
        except Exception, e:
            # print(str(e))
            ret.code = 1007
            ret.msg = "数据库操作异常!"
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())


# 找回忘记密码(重设密码)
@csrf_exempt
def forgetregist(request):
    ret = ReturnJ()
    db = DB.getDB()
    ret.id_user = ''
    try:
        info = INFO(request)
        info.checkPostEmpty('tel_number', 'identity_code', "new_pwd")
        info.cdate = info.tick()
        sql = sqlr("update user set cpwd=$new_pwd where tel_number=$tel_number", info)
        db.execute(sql)
        ret.msg = "密码修改成功"
        try:
            sql = sqlr("select * from user where tel_number=$tel_number", info)
            n, rows = db.query(sql)
            if n <= 0:
                ret.code = 1001
                ret.msg = "用户不存在!"
            else:
                info.id = rows[0]['id']
                data = verifycode(info.tel_number, info.identity_code)
                if data['code'] == 200:
                    try:
                        sql = sqlr("update user set cpwd=$new_pwd where id=$id", info)
                        db.execute(sql)
                        ret.id_user = info.id
                    except Exception, e:
                        # print(str(e))
                        ret.code = 1007
                        ret.msg = "数据库操作异常!"
                else:
                    ret.code = 1003
                    ret.msg = "验证码错误!"
        except Exception, e:
            # print(str(e))
            ret.code = 1007
            ret.msg = "数据库操作异常!"
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res


# 获取用户所有信息
@csrf_exempt
def user_base(request):
    ret = ReturnJ()
    ret.user_info = {}
    ret.user_count = {}
    ret.user_finance = {}
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user")
        id = info.id_user
        ret.user_info = get_user_info(id)
        ret.user_count = get_user_counter(id)
        ret.user_finance = get_user_finance(id)
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res


# 获取用户统计信息(点赞/被关注/访问/)
@csrf_exempt
def user_counter(request):
    ret = ReturnJ()
    ret.user_count = {}
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user")
        ret.user_count = get_user_counter(info.id_user)

    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())


# 获取该用户关注的用户清单
@csrf_exempt
def user_payattention_list(request):
    ret = ReturnJ()
    ret.payattention_list = []
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user", 'id_my')
        ret.payattention_list = get_payattention_list(info.id_user, info.id_my)

    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())


# 获取关注该用户的粉丝清单
@csrf_exempt
def user_fans_list(request):
    ret = ReturnJ()
    ret.fans_list = []
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user", 'id_my')
        ret.fans_list = get_fans_list(info.id_user, info.id_my)

    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())


# 获取主播视频列表
@csrf_exempt
def user_videolist(request):
    ret = ReturnJ()
    ret.videolist = []
    try:
        info = INFO(request)
        info.checkPostEmpty("cur_page", "pagesize", "id_user")
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        ret.videolist = get_video_list(info)

    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())


# 获取该用户关注的主播的视频
@csrf_exempt
def user_payattention_actor_video_list(request):
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty("cur_page", "pagesize", "id_user")
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        ret.payattention_actor_video_list = get_payattention_actor_video_list(info)

    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())


# 获取该用户的消费日志
@csrf_exempt
def user_log_pay(request):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        info = INFO(request)
        info.checkPostEmpty("cur_page", "pagesize", "id_user")
        info.cur_page = str(int(info.cur_page) * int(info.pagesize) + 1)
        ret.user_log_pay = get_log_pay(info)

    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())


# 用户点赞\关注\取消关注\访问
@csrf_exempt
def user_action(request, id):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        info = INFO(request)
        info.checkPostEmpty("ctype", "id_video")
        info.cdate = utils_datetime.todaytime()
        info.object=info.id_video
        ret=user_action_execute(id,info,ret=ret)
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())

# 用户点赞
@csrf_exempt
def user_praise(request, id):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        info = INFO(request)
        info.checkPostEmpty("room_num","id_actor")

        sql1 = sqlr("UPDATE video set nlike=nlike+1 WHERE room_num=$room_num",info)
        db.execute(sql1)

        sql2 = sqlr("select *  from user_count  where id_user=$id_actor ", info)
        n, rows = db.query(sql2)
        if n == 0:
            info.id = maxid('user_count', 'id')
            sql3 = "insert user_count(id,id_user,n_payattention,n_fans,n_access,n_praise) values(%s,%s,0,0,0,0)" % (
                info.id, info.id_actor)
            db.execute(sql3)
        sql4 = sqlr("UPDATE user_count set n_praise=n_praise+1 WHERE id_user=$id_actor",info)
        db.execute(sql4)
        # info.cdate = utils_datetime.todaytime()
        # ret=user_action_execute(id,info,ret=ret)
    except Exception, e:
        print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())

# 关注\取消关注
@csrf_exempt
def user_payattention(request, id):
    ret = ReturnJ()
    info = INFO(request)
    info.checkPostEmpty("ctype", "id_user")

    if (str(id) != str(info.id_user)):
        if int(info.ctype) == 0:
            info.ctype = 4
        elif int(info.ctype) == 1:
            info.ctype = 3
        info.id_object = info.id_user
        info.cdate = utils_datetime.todaytime()
        ret = user_action_execute(id, info, ret=ret)
    else:
        ret.msg = "不能关注自己"
        ret.code = 1101
    return HttpResponse(ret.toJson())

# 访问
@csrf_exempt
def user_access(request, id):
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user")
        info.ctype=2
        info.id_object=info.id_user
        info.cdate = utils_datetime.todaytime()
        ret=user_action_execute(id,info,ret=ret)

        ret.user = get_user_info(info.id_user,id_user=id)

    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())

# 最近访客
@csrf_exempt
def user_access_list(request, id):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        info = INFO(request)
        info.checkPostEmpty('cur_page', 'pagesize')
        info.cur_page = str(int(info.cur_page) * int(info.pagesize) + 1)
        sql = "select * from user where id in (select id_b from user_act where id_a=%s and act=2 order by cdate desc) limit %s,%s"%(id, info.cur_page,info.pagesize)
        # print sql
        n, rows = db.query(sql)
        ret.access_list = out_farmat_users(rows,0,id=id)
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())

# 送礼
@csrf_exempt
def user_givegift(request, id):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        info = INFO(request)
        info.checkPostEmpty('id_user', 'id_gift')
        gift_row=get_gift_info(info.id_gift)

        sql = sqlr("select * from user where id in (select * from user_act where id_a=%s and id_b=%s and act=2 order by cdate desc ) limit %s,%s", info)
        n, rows = db.query(sql)
        ret.access_list = out_farmat_users(rows,0,id=id)
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())

# user_consume
@csrf_exempt
def user_consume_insert(request, id):
    pass

#添加用户统计信息
def user_action_execute(id,info,ret=0):
    db = DB.getDB()
    if int(info.ctype) == 0:
        # rds.add("room_id_like_" + info.id_object, id+"_"+info.tick())  # 点赞数
        # rds.add("%s%s"%("room_id_like_",info.id_object),"%s%s"%(id,info.tick()))  # 点赞数
        return ret
    if int(info.ctype) == 3:
        sql = "select * from  user_act where id_a=%s and id_b=%s and act=1" % (id, info.id_object)
        n,rows = db.query(sql)
        if n==0:
            ret.code=1010
            ret.msg="未关注"
            return ret
        sql = "delete from  user_act where id_a=%s and id_b=%s and act=1" % (id, info.id_object)
    else:
        if int(info.ctype) == 4:
            sql = "select * from  user_act where id_a=%s and id_b=%s and act=1" % (id, info.id_object)
            n,rows = db.query(sql)
            # sql = "update user_count set n_payattention=%s,n_fans=%s where id=%s" %()
            # db.execute(sql)
            if n>0:
                ret.code=1010
                ret.msg="已经关注"
                return ret
        if int(info.ctype) == 1:
            t_act=0
        elif int(info.ctype) == 4:
            t_act=1
        elif int(info.ctype) == 2:
            t_act=2
        info.id = maxid('user_act', 'id')
        sql = "insert user_act(id,id_a,id_b,act,cdate) values(%s,%s,%s,%s,%s)" % (
        info.id, id, info.id_object, t_act, info.cdate)
    db.execute(sql)
    row_a = get_user_counter(id)
    if len(row_a) == 0:
        info.id = maxid('user_count', 'id')
        sql = "insert user_count(id,id_user,n_payattention,n_fans,n_access,n_praise) values(%s,%s,0,0,0,0)" % (
        info.id, id)
        db.execute(sql)
        row_a['id_user_count'] = info.id
        row_a['id_user'] = id
        row_a['n_payattention'] = 0
        row_a['n_fans'] = 0
        row_a['n_access'] = 0
        row_a['n_praise'] = 0
    row_b = get_user_counter(info.id_object)
    if len(row_b) == 0:
        info.id = maxid('user_count', 'id')
        sql = "insert user_count(id,id_user,n_payattention,n_fans,n_access,n_praise) values(%s,%s,0,0,0,0)" % (
        info.id, info.id_object)
        db.execute(sql)
        row_b['id_user_count'] = info.id
        row_b['id_user'] = info.id_user
        row_b['n_payattention'] = 0
        row_b['n_fans'] = 0
        row_b['n_access'] = 0
        row_b['n_praise'] = 0
    if int(info.ctype) == 1:
        row_b['n_praise'] += 1
    elif int(info.ctype) == 4:
        row_a['n_payattention'] += 1
        row_b['n_fans'] += 1
    elif int(info.ctype) == 2:
        row_b['n_access'] += 1
    elif int(info.ctype) == 3:
        row_a['n_payattention'] -= 1
        row_b['n_fans'] -= 1
    sql = "update user_count set n_payattention=%s,n_fans=%s,n_access=%s,n_praise=%s where id=%s" % (
    row_b['n_payattention'], row_b['n_fans'], row_b['n_access'], row_b['n_praise'], row_b['id_user_count'])
    db.execute(sql)

    sql = "update user_count set n_payattention=%s,n_fans=%s where id=%s" % (
    row_a['n_payattention'], row_a['n_fans'], row_a['id_user_count'])
    db.execute(sql)
    return ret

# 修改用户信息
@csrf_exempt
def changeuserinfo(request):
    db = DB.getDB()
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user","nickname","img","signature")


        # 更新网易云用户信息

        sql_info = sqlr("select * from user where id=$id_user", info)
        n, rows_info = db.query(sql_info)
        if n>0:
            # print info.img
            neteas_update_info = p.updateUinfo(accid=rows_info[0]['accid'],name=info.nickname,icon=info.img)
            # print neteas_update_info
            if neteas_update_info['code'] == 200:
                # 更新服务器用户信息
                if info.img != '':
                    info.img = info.img[len(datais.url_img):]
                try:
                    sql = sqlr("update user set nickname=$nickname,img=$img,signature=$signature,gender=$gender where id=$id_user", info)
                    db.execute(sql)
                    ret.user = get_user_user(info.id_user)
                except Exception,e:
                    # print(str(e))
                    ret.code = 1007
                    ret.msg = "数据库操作异常!"
            else:
                ret.code = neteas_update_info['code']
                ret.msg = "使用网易云信异常!" + str(neteas_update_info)

    except Exception,e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res

# 主播认证
@csrf_exempt
def authentication(request):
    db = DB.getDB()
    ret = ReturnJ()
    try:
        info = INFO(request)
        info.checkPostEmpty("id_user","realname","height","tel_number","department","address","idcard","md_A","md_B","md_C","is_actor")


        if info.md_A != '':
            info.md_A = info.md_A[len(datais.url_img):]
        if info.md_B != '':
            info.md_B = info.md_B[len(datais.url_img):]
        if info.md_C != '':
            info.md_C = info.md_C[len(datais.url_img):]
        info.id_idcard_img = maxid("user_idcard", "id")
        info.md5 = {'md_A':info.md_A,'md_B':info.md_B,'md_C':info.md_C}
        # print str(info.md5)

        info.md5 = '\'%s\''%(json.dumps(info.md5))

        # print info.md5


        try:

            # 先查询下数据库看此用户id是否有效
            user_info = sqlk("select * from user where id=$id", id=info.id_user)
            n, user_info = db.query(user_info)
            if n>0:

                # 插入身份证图片表
                sql_insert_card = "insert into user_idcard(id,md5) VALUES (%s,%s)" % (info.id_idcard_img, info.md5)
                db.execute(sql_insert_card)

                # 先查询下数据库看此用户是否已申请过
                actor_info = sqlk("select * from actor where id=$id", id=info.id_user)
                m, actor_rows = db.query(actor_info)
                # 设置认证状态为认证中...
                info.verify_status=4
                if m == 0:
                    # 主播表中还没有主播信息，插入主播信息
                    sql_insert_actor = sqlr(
                        "insert into actor(id, realname, height,department,person_desc, honor, works_url, idcard, id_idcard_img, is_actor,verify_status)"
                        " VALUES ($id_user,$realname,$height,$department,$person_desc,$honor,$works_url,$idcard,$id_idcard_img,$is_actor,$verify_status)",
                        info)
                    db.execute(sql_insert_actor)
                else:
                    # 主播已申请过，再次申请,更新主播表
                    sql_update_actor = sqlr("update actor set realname=$realname,height=$height,department=$department,"
                                            "person_desc=$person_desc, honor=$honor, works_url=$works_url, idcard=$idcard,"
                                            " id_idcard_img=$id_idcard_img, is_actor=$is_actor,verify_status=$verify_status where id=$id_user", info)
                    db.execute(sql_update_actor)

                # 更新用户表中地址  手机号不能改，改了用户表手机号就会无法登录
                if info.gender == "":
                    info.gender = user_info[0]['gender']
                sql_update_user = sqlr("update user set address=$address,gender=$gender where id=$id_user",info)
                db.execute(sql_update_user)
                ret.msg = "信息提交成功，请等待审核"
            else:
                ret.msg = "此用户不存在"
                ret.code = 1001
        except Exception,e:
            # print(str(e))
            ret.code = 1007
            ret.msg = "数据库操作异常!"

    except Exception,e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())
@csrf_exempt
def trading(request):
    db = DB.getDB()
    ret = ReturnJ()
    # list_trading = []
    try:
        info = INFO(request)
        info.checkPostEmpty("cur_page", "pagesize", "id_user",'type')
        # info.cur_page = str(int(info.cur_page) * int(info.pagesize) + 1)
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        info.id = int(info.id_user)
        info.page = int(info.cur_page)
        info.size = int(info.pagesize)
        # user_consume = sqlr('select * from user_consume where id_sender=$id_user or id_user_receive=$id_user',info)
        # n,rows1 = db.query(pay_order)
        # n,rows2 = db.query(user_consume)
        # ret.trading = get_pay_trading(id,page,pagesize)
        # ret.user_consume = get_user_consume(id)
        # ret.user_finance = get_user_finance(id)
        # print rows
        # sql = "select * from (select o.id_user as id ,o.create_time as time ,o.money as money ,'充值' as type ,1 as status from pay_order o where id_user=%d and o.order_status=1 union all select c.id_user_send as id ,c.cdate as time,c.gift_fmoney as money , '送礼物' as type, 1 as status FROM user_consume c where c.id_user_send=%d union all select d.id_user_send as id ,d.cdate as time,d.gift_fmoney as money , '收礼物' as type,1 as status FROM user_consume d where d.id_user_receive=%d union all select g.id_actor as id ,g.cdate as time ,g.take_fmoney as money , '提现' as type, g.state as status FROM user_getcash g where g.id_actor=%d) as T order by time desc limit %d,%d" % (
        # int(id), int(id), int(id), int(id), int(page), int(pagesize))
        # print 11111111111
        # sql = "select money* %d from pay_order  WHERE id_user=%d"%(10, info.id)
        # n, rows = db.query(sql)
        # print n,rows
        # print rows[0]['money'] * 10
        # sql = 'select * from (select o.id_user as id ,o.create_time as time ,o.money as money ,1 as status from pay_order o where id_user=%d and o.order_status=1 union all select c.id_user_send as id ,c.cdate as time,c.gift_fmoney as money ,1 as status FROM user_consume c where c.id_user_send=%d union all select d.id_user_send as id ,d.cdate as time,d.gift_fmoney as money ,1 as status FROM user_consume d where d.id_user_receive=%d union all select g.id_actor as id ,g.cdate as time ,g.take_fmoney as money , g.state as status FROM user_getcash g where g.id_actor=%d) as T order by time desc limit %d,%d'%(217,217,217,217,0,1)
        sql = "select * from (select o.id_user as id ,o.create_time as time ,o.money as money  ,0 as type ,1 as status from pay_order o where id_user=%d and o.order_status=1 union all select c.id_user_send as id ,c.cdate as time,c.gift_fmoney as money , 1 as type, 1 as status FROM user_consume c where c.id_user_send=%d union all select d.id_user_send as id ,d.cdate as time,d.gift_fmoney as money , 2 as type,1 as status FROM user_consume d where d.id_user_receive=%d union all select g.id_actor as id ,g.cdate as time ,g.take_fmoney as money , 3 as type, g.state as status FROM user_getcash g where g.id_actor=%d) as T order by time desc limit %d,%d" %(info.id,info.id,info.id,info.id,info.page,info.size)
        # print sql
        n, rows = db.query(sql)
        # print n
        # for row in rows:
        #     list_trading.append(row)
        # return list_trading

        # dict_trading = out_farmat_trading(rows)
        # print rows[0]

        ret.dict_trading = out_farmat_trading(rows, info.type)
        ret.code = 200
        ret.msg = '查询成功'
    except:
        ret.code = 1007
        ret.msg = "数据库操作异常!"
    return HttpResponse(ret.toJson())


@csrf_exempt
def look_video(request):
    db = DB.getDB()
    ret = ReturnJ()
    # list_trading = []
    try:
        info = INFO(request)
        info.checkPostEmpty("room_num")
        sql = sqlr("update video set nlooked=nlooked+1 where room_num=$room_num", info)
        db.execute(sql)

        ret.code = 200
        ret.msg = '查看成功'
    except:
        ret.code = 1007
        ret.msg = "数据库操作异常!"
    return HttpResponse(ret.toJson())





